//
//  dayDetailTableViewCell.m
//  SmartRoadShow
//
//  Created by  ibokan on 10-9-20.
//  Copyright 2010 simonwang142232@gmail.com. All rights reserved.
//

#import "dayDetailTableViewCell.h"
#import <QuartzCore/QuartzCore.h>
#import "CacheManager.h"
#import "PushedCitys.h"
#import "SmartRoadShowAppDelegate.h"
#import "Reachability.h"

@implementation dayDetailTableViewCell
@synthesize imageView1, indexPath ,delegate;
@synthesize sortLabel, timeLabel, infoLabel;
@synthesize attentionButton, detailButton,typeFlag;

enum buttonState {
	red,
	gary,
};

-(id) initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
	if(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])
	{
		
		imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(18, 24, 80, 80)];
		imageView1.layer.cornerRadius = 5;
		imageView1.layer.masksToBounds = YES;
		[imageView1 setBackgroundColor:[UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.8]];
		[self.contentView addSubview:imageView1];
		[imageView1 release];
		
		sortLabel = [[UILabel alloc] initWithFrame:CGRectMake(108, 18, 180, 25)];
		sortLabel.backgroundColor = [UIColor clearColor];
		sortLabel.font = [UIFont boldSystemFontOfSize:13];
		[self.contentView addSubview:sortLabel];
		[sortLabel release];
		
		infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(108, 40, 180, 30)];
		infoLabel.backgroundColor = [UIColor clearColor];
		infoLabel.textColor = [UIColor blackColor];
		[infoLabel setNumberOfLines:0];
		infoLabel.font = [UIFont boldSystemFontOfSize:12.5];
		[self.contentView addSubview:infoLabel];
		[infoLabel release];
		
		timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(108, 63, 180, 25)];
		timeLabel.backgroundColor = [UIColor clearColor];
		timeLabel.textColor = [UIColor blackColor];
		timeLabel.font = [UIFont boldSystemFontOfSize:12.5];
		[self.contentView addSubview:timeLabel];
		[timeLabel release];
		
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button addTarget:self action:@selector(seeDetailInfo) forControlEvents:UIControlEventTouchUpInside];
		button.frame = CGRectMake(258, 90, 40, 40);
		[button setImage:[UIImage imageNamed:@"accessory.png"] forState:UIControlStateNormal];
		[self.contentView addSubview:button];
	}
	
	return self;
}

- (void)setTimeLabelText:(NSString *)begin End:(NSString *)end{
	timeLabel.text = [NSString stringWithFormat:@"%@ 至 %@",begin,end];
	endTime = [end retain];
}

- (void)push{
	
	Reachability *internetReach = [Reachability reachabilityForInternetConnection];
	[internetReach startNotifier];	
	NetworkStatus netStatus = [internetReach currentReachabilityStatus];
	
	if (netStatus) {
		
		NSLog(@"push %@   %@",pushCity,pushTime);
		NSString* messageStr = (ifConcern == YES)? @"取消": @"加入";
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:nil
														message:[NSString stringWithFormat: @"您是否将该活动%@时间提醒?", messageStr]
													   delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
		[alert show];
		[alert release];
	}
	else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"本功能需要网络支持，请检查网络连接！"
													   delegate:nil cancelButtonTitle:@"确定"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];		
	}
	
}

- (void)seeDetailInfo{
	[delegate seeDetailInfoForIndexPath:self.indexPath];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	
	SmartRoadShowAppDelegate *appDelegate = (SmartRoadShowAppDelegate *)[[UIApplication sharedApplication] delegate];
	NSString* token = appDelegate.token;
	
	NSLog(@"%@",token);
	
	if (buttonIndex == 0) {
		//已经关注，点击取消关注，变成灰色
		
		if (buttonState == red) {
			ifConcern = NO;
			[attentionButton setImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
			//[PushedCitys deleteWhileCity:pushCity Time:pushTime];
			[PushedCitys deleteById:pushNewsId];
			buttonState = gary;
			
			
			NSURL* url = [NSURL URLWithString:kCancelSendURL];
			NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
			[request setTimeoutInterval:30];
			[request setHTTPMethod:@"POST"];
			
			NSString* postStr = nil;
			if(typeFlag == 1){
				postStr = [NSString stringWithFormat:@"token=%@&type=1&city=%@&time=%@&sendid=0", token, pushCity, pushTime];
			}
			//艺术地图
			else if(typeFlag == 2){
				postStr = [NSString stringWithFormat:@"token=%@&type=2&city=%@&time=%@&sendid=0&title=%@", token, pushCity, pushTime,pushTitle];
			}
			NSLog(@"postStr : %@",postStr);

			
			
			NSData* postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
			[request setHTTPBody:postData];
			
			[NSURLConnection  sendSynchronousRequest:request returningResponse:nil error:nil];
			
			[request release];
			
			
		}
		//未被关注，点击关注，变成红色
		else if (buttonState == gary) {
			ifConcern = YES;
			[attentionButton setImage:[UIImage imageNamed:@"star_red.png"] forState:UIControlStateNormal];
			buttonState = red;
			//[PushedCitys insertPushedCityWithCity:pushCity Time:pushTime];
			[PushedCitys insertPushedCityWithId:pushNewsId City:pushCity Time:pushTime Title:pushTitle];
			
			NSString *url_string = kSendURL;
			NSURL *url= [NSURL URLWithString:url_string];
			NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
			[request setTimeoutInterval: 30];
			[request setHTTPMethod:@"POST"];
			
			NSString* postStr = nil;
			if(typeFlag == 1){
				postStr = [NSString stringWithFormat:@"token=%@&type=1&city=%@&time=%@&sendid=1", token, pushCity, pushTime];
			}
			//艺术地图
			else if(typeFlag == 2){
				postStr = [NSString stringWithFormat:@"token=%@&type=2&city=%@&time=%@&sendid=1&title=%@", token, pushCity, pushTime,pushTitle];
			}
			
			
			NSData* postData = [postStr dataUsingEncoding:NSUTF8StringEncoding];
			[request setHTTPBody:postData];

			
			[NSURLConnection 
			 sendSynchronousRequest:request 
			 returningResponse: nil 
			 error: nil];
			
			[request release];
			
			
		}
		attentionButton.frame = attentionButtonFrame;
	}
}

- (void)setPushById:(NSString*)newsId City:(NSString *)city Time:(NSString *)time Title:(NSString *)title{
	
	pushNewsId = [newsId retain];
	pushCity = [city retain];
	pushTime = [time retain];
	pushTitle = [title retain];
	
	NSString *stationTime = endTime;
	NSString *currentTime = [[NSString stringWithFormat:@"%@",[NSDate date]] substringToIndex:10];
	
	BOOL result = [stationTime compare:currentTime] == NSOrderedDescending || ![currentTime isEqual:currentTime];
	
	if (result) {
		//未被关注，灰色
		if (![PushedCitys findById:pushNewsId]) {			
			ifConcern = NO;
			attentionButton  = [UIButton buttonWithType:UIButtonTypeCustom];
			[attentionButton addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
			attentionButton.layer.cornerRadius = 8;
			attentionButton.frame = attentionButtonFrame;
			[attentionButton setBackgroundImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
			
			buttonState = gary;
			[self.contentView addSubview:attentionButton];
		}
		//已经关注，红色
		else {
			ifConcern = YES;
			attentionButton  = [UIButton buttonWithType:UIButtonTypeCustom];
			[attentionButton addTarget:self action:@selector(push) forControlEvents:UIControlEventTouchUpInside];
			attentionButton.layer.cornerRadius = 8;
			attentionButton.frame = attentionButtonFrame;
			
			[attentionButton setBackgroundImage:[UIImage imageNamed:@"star_red.png"] forState:UIControlStateNormal];
			buttonState = red;
			[self.contentView addSubview:attentionButton];
		}
	}
	//过期的，灰色不可点击
	else {
		attentionButton  = [UIButton buttonWithType:UIButtonTypeCustom];
		[attentionButton addTarget:self action:nil forControlEvents:UIControlEventTouchUpInside];
		attentionButton.layer.cornerRadius = 8;
		attentionButton.frame = attentionButtonFrame;
		[attentionButton setBackgroundImage:[UIImage imageNamed:@"star.png"] forState:UIControlStateNormal];
		[self.contentView addSubview:attentionButton];
	}
	
	
}

- (void)setImageWithURL:(NSString *)url{
	UIImage *image = [CacheManager getImageAccordingToURLString:url];
	if (image != nil) {
		[imageView1  setImage:image];
		imageView1.contentMode = UIViewContentModeScaleAspectFit;
		[imageView1 setBackgroundColor:[UIColor clearColor]];
	}
	else{
		
		ImageDownloader* downLoader = [[[ImageDownloader alloc] init] autorelease];
		downLoader.imageReceiver = self;
		downLoader.imageURLString = url;
		[downLoader startDownloadWithImageURLString:url];
	}
	
}

-(void)imageDownloader:(ImageDownloader*)downloader didReceiveImage:(UIImage*)image{
	[imageView1 setImage:image];
	imageView1.contentMode = UIViewContentModeScaleAspectFit;
	[CacheManager setImage:image withImageURLString:downloader.imageURLString];
	[imageView1 setBackgroundColor:[UIColor clearColor]];

}

- (void)setCellStyle:(NSInteger)type{
	switch (type) {
		case 0:
			self.layer.contents = (id)[UIImage imageNamed:@"cellType2.png"].CGImage;
			break;
		case 1:
			self.layer.contents = (id)[UIImage imageNamed:@"cellType1.png"].CGImage;
			break;
		case 2:
			self.layer.contents = (id)[UIImage imageNamed:@"cellType1.png"].CGImage;
			break;
		default:
			break;
	}
}

- (void)dealloc 
{
    [super dealloc];
}


@end
